<?php
declare (strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;

class checkPayTask extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('checkpaytask')
            ->setDescription("抢购订单自动签收任务\t检查付款自动签收时间规则");
    }

    protected function execute(Input $input, Output $output)
    {
        $sql = "SELECT * FROM sy_goods_rush WHERE NOW()>(update_time + INTERVAL 1 HOUR) AND state=3";
        $sql_result = Db::query($sql, []);
        if (!empty($sql_result) && count($sql_result) > 0) {
            foreach ($sql_result as $k => $v) {
                // 启动事务
                Db::startTrans();
                try {
                    $gid = $v['id'];
                    $rusher_id = $v['rusher_id'];
                    $belong_id = $v['belong'];
                    $order_info = Db::name('user_order')->where('id', $v['current_order_id'])->find();
                    if(empty($order_info)){
                        $output->writeln("order_info 自动签收，更新收益异常:gid:" . $gid."--->>>>orderinfo未找到");
                        continue;
                    }
                    $price = $order_info['g_price'];
                    $test_result = Db::name('user_order_publish')
                        ->where('order_no', $v['publish_order_no'])
                        ->where('uid', $belong_id)
                        ->update(['hassale' => 1]);
                    if ($test_result) {
                        $output->writeln($gid . "==>ok");
                    } else {
                        $output->writeln("test_result自动签收，更新收益异常:gid:" . $gid);
                    }
                    $r1 = Db::execute("UPDATE sy_goods_rush SET state=0,last_belong=belong,belong=rusher_id,rusher_id=0 WHERE id=" . $gid);

                    $r2 = Db::execute("UPDATE sy_user_order SET pay_state=1 WHERE state=1 AND uid={$rusher_id} AND id={$order_info['id']}");

                    $userinfo = Db::name('user')->where('id', $rusher_id)->find();
                    if (!empty($userinfo)) {
                        // 更新推荐人收益
                        if ($userinfo['level1_recommender'] > 0) {
                            // 获取收益率
                            $rate = Db::name('other_config')->where('id', 2)->find();
                            if (!empty($rate)) {
                                $rate = $rate['value3'];
                            } else {
                                $rate = 3;
                            }
                            $income = (int)($price * $rate * 0.001);
                            $r1income = Db::name('user_income')->where('id', $userinfo['level1_recommender'])->find();
                            $beforeTotal = 0;
                            $beforeAvaliable = 0;
                            if (!empty($r1income)) {
                                $beforeTotal = $r1income['income_total'];
                                $beforeAvaliable = $r1income['income'];
                                $r3 = Db::execute("UPDATE sy_user_income SET income_total=income_total+?,income=income+?,income_order_count=income_order_count+1 WHERE id=?", [$income, $income, $userinfo['level1_recommender']]);
                            } else {
                                $r3 = Db::execute("INSERT INTO sy_user_income (id,income_total,income,income_order_count) VALUES (?,?,?,1)", [$userinfo['level1_recommender'], $income, $income]);
                            }
                            $r4 = Db::execute("INSERT INTO sy_user_income_record (uid,order_id,order_no,fans_level,fans_uid,before_total_income,before_available_income,income,rate) 
            VALUES (?,?,?,?,?,?,?,?,?)", [$userinfo['level1_recommender'], $order_info['id'], $order_info['order_no'], 1, $userinfo['id'], $beforeTotal, $beforeAvaliable, $income, $rate]);

                            if($r1 && $r2 && $r3 && $r4){
                                Db::commit();
                            }else{
                                Db::rollback();
                                $output->writeln('rollback====>>>$r1 && $r2 && $r3 && $r4:gid:' . $gid."r1={$r1}||r2={$r2}||r3={$r3}||r4={$r4}");
                            }

                        }

                        if ($userinfo['level2_recommender'] > 0) {
                            // 获取收益率
                            $rate = Db::name('other_config')->where('id', 3)->find();
                            if (!empty($rate)) {
                                $rate = $rate['value3'];
                            } else {
                                $rate = 2;
                            }
                            $income = (int)($price * $rate * 0.001);
                            $r1income = Db::name('user_income')->where('id', $userinfo['level2_recommender'])->find();
                            $beforeTotal = 0;
                            $beforeAvaliable = 0;
                            if (!empty($r1income)) {
                                $beforeTotal = $r1income['income_total'];
                                $beforeAvaliable = $r1income['income'];
                                $r3 = Db::execute("UPDATE sy_user_income SET income_total=income_total+?,income=income+?,income_order_count=income_order_count+1 WHERE id=?", [$income, $income, $userinfo['level2_recommender']]);
                            } else {
                                $r3 = Db::execute("INSERT INTO sy_user_income (id,income_total,income,income_order_count) VALUES (?,?,?,1)", [$userinfo['level2_recommender'], $income, $income]);
                            }
                            $r4 = Db::execute("INSERT INTO sy_user_income_record (uid,order_id,order_no,fans_level,fans_uid,before_total_income,before_available_income,income,rate) 
            VALUES (?,?,?,?,?,?,?,?,?)", [$userinfo['level2_recommender'], $order_info['id'], $order_info['order_no'], 2, $userinfo['id'], $beforeTotal, $beforeAvaliable, $income, $rate]);

                            if($r1 && $r2 && $r3 && $r4){
                                Db::commit();
                            }else{
                                Db::rollback();
                                $output->writeln('rollback====>>>$r1 && $r2 && $r3 && $r4:gid:' . $gid."r1={$r1}||r2={$r2}||r3={$r3}||r4={$r4}");
                            }
                        }

                    }

                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $output->writeln("rollback====>>>自动签收，更新收益异常:gid:" . $gid.'=='.$e->getMessage());
                    continue;
                }


            }
        }

        if (count($sql_result) > 0) {
            $output->writeln("自动签收订单数:" . count($sql_result) . "=>>>" . date("Y-m-d H:i:s", time()));
        }


    }
}
